package simpleStructure;

/**
 * front == tail 为空
 * （tail+1)%capacity == front 满了
 * queue的真是capacity 为 展示capacity + 1 浪费了一个空间。
 *
 * @param <E>
 */
public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front, tail;
    private int size;

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return tail == front;
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity +1];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front)%data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        if (isEmpty()){
            throw new RuntimeException("queue is empty");
        }
        E datum = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        if (size <= getCapacity()/4 && getCapacity()>4){
            resize(getCapacity()/2);
        }
        return datum;
    }

    @Override
    public E getFront() {
        if (isEmpty()){
            throw new RuntimeException();
        }
        return data[front];
    }

    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append(String.format("Queue size=%d, capacity=%d, front [", size, getCapacity()));
        for (int i = front; i != tail; i = (i+1)%data.length) {
            res.append(data[i]);
            if ((i+1)%data.length != tail) {
                res.append(",");
            }
        }
        res.append("] tail");

        return res.toString();
    }
}
